package com.cloud.file.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.cloud.common.response.ApiResponse;
import com.cloud.file.config.AliOSSConfig;
import com.cloud.file.service.FileService;
import com.cloud.file.domain.vo.FileUpInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;

@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private OSS client;

    @Autowired
    private AliOSSConfig aliOSSConfig;

    @Override
    public ApiResponse<FileUpInfoVO> getCommonToken() throws Exception{
        ApiResponse<FileUpInfoVO> resp = new ApiResponse<>();
        long expireTime = 600;
        long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
        Date expiration = new Date(expireEndTime);
        PolicyConditions policyConds = new PolicyConditions();
        policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
        String fileDir = aliOSSConfig.getFileDir();
        policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, fileDir);
        String postPolicy = client.generatePostPolicy(expiration, policyConds);
        byte[] binaryData = postPolicy.getBytes();
        String encodedPolicy = BinaryUtil.toBase64String(binaryData);
        String postSignature = client.calculatePostSignature(postPolicy);
        FileUpInfoVO fileUpInfoVO = new FileUpInfoVO();
        fileUpInfoVO.setAccessId(aliOSSConfig.getAccessKeyId());
        fileUpInfoVO.setPolicy(encodedPolicy);
        fileUpInfoVO.setSignature(postSignature);
        fileUpInfoVO.setDir(fileDir);
        fileUpInfoVO.setHost(aliOSSConfig.getHost());
        fileUpInfoVO.setExpire(String.valueOf(expireEndTime / 1000));
        fileUpInfoVO.setCallback(prepareCallBackBody(aliOSSConfig.getCallback()));
        resp.setData(fileUpInfoVO);
        return resp;
    }

    private String prepareCallBackBody(String callbackUrl) {
        JSONObject jasonCallback = new JSONObject();
        jasonCallback.put("callbackUrl", callbackUrl);
        jasonCallback.put("callbackBody",
                "filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}");
        jasonCallback.put("callbackBodyType", "application/x-www-form-urlencoded");
        return BinaryUtil.toBase64String(jasonCallback.toJSONString().getBytes());
    }

}
